let arr = [""];
const COS = require('../../utils/cos-wx-sdk-v5.js')
const config = require('../../utils/config.js')
const cos = new COS({
  getAuthorization: function(params, callback) { //获取签名 必填参数

    // 方法一（推荐）服务器提供计算签名的接口
    /*
    wx.request({
        url: 'SIGN_SERVER_URL',
        data: {
            Method: params.Method,
            Key: params.Key
        },
        dataType: 'text',
        success: function (result) {
            callback(result.data);
        }
    });
    */

    // 方法二（适用于前端调试）
    let authorization = COS.getAuthorization({
      SecretId: config.SecretId,
      SecretKey: config.SecretKey,
      Method: params.Method,
      Key: params.Key
    });
    callback(authorization);
  }
});

Page({

  data: {
    arr,
    activeTab: null,
    addWhat: 0,
    preArr: null,
    plus_img: "/icon/plus.png",
    minus_img: "/icon/minus.png",
    title_img: "/icon/title.png",
    text_img: "/icon/text.png",
    img_img: "/icon/img.png",
  },
  //删除按钮
  deleteItem(e) {
    let index = e.currentTarget.dataset.index;
    this.deleteArr(index);
  },
  //添加按钮
  plusItem(e) {
    let index = e.currentTarget.dataset.index;
    if (this.data.activeTab == index) {
      this.setData({
        activeTab: null
      })
      return
    } else {
      this.setData({
        activeTab: index
      })
    }

  },
  //1添加标题 2添加正文 3添加图片
  addSth(e) {
    this.setData({
      addWhat: e.currentTarget.dataset.types
    })
    if (this.data.addWhat == 3) this.imageAdd();
  },
  //保存发表
  savePost() {
    return
    let newArr;
    newArr = this.data.arr.filter(item => item != "");

    if (newArr.length == 0) return

    if (newArr[0].includes("[标题]",0)){
      let key = newArr[0];
      let random = Math.random().toFixed(4).toString();

      let KEY = key + random;
      let str = JSON.stringify(newArr);
      console.log(str)

      cos.putObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: "cc/" + KEY,
        Body: str,
      }, function (err, data) {
        console.log(err || data);
      });
    }else{
      wx.showToast({
        title: '请先填写标题',
        icon:"none"
      })
    }

  
    console.log(newArr.toString())

  },

  /**
   * 预览 数组去空之后传值
   */
  preView() {
    if (this.data.arr.length == 1) {
      wx.showToast({
        title: '您还没添加任何东西',
        icon: "none"
      })
      return
    }
    let newArr;
    newArr = this.data.arr.filter(item => item != "");
    console.log(newArr);

    this.setData({
      preArr: newArr
    })
  },
  //预览返回按钮
  comeBack() {
    this.setData({
      preArr: null
    })
  },

  //修改数组函数
  changeArr(text) {
    let curIndex = this.data.activeTab;
    let arr = this.data.arr;
    arr.splice(curIndex, 0, text);
    arr.splice(curIndex, 0, "");
    this.setData({
      arr: arr
    })
  },

  //删除数组元素
  deleteArr(index) {
    let arr = this.data.arr;
    arr.splice(index, 2);
    this.setData({
      arr: arr
    })
  },
  /**    
   *添加标题模块
   */
  titleText(e) {
    this.changeArr(e.detail);
    this.setData({
      addWhat: null,
      activeTab: null
    })
  },
  closeTitle() {
    this.setData({
      addWhat: null
    })
  },
  /**
   * 添加正文模块
   */
  textValue(e) {
    this.changeArr(e.detail);
    this.setData({
      addWhat: null,
      activeTab: null
    })
  },
  closeText() {
    this.setData({
      addWhat: null
    })
  },
  /**
   * 添加图片模块
   */
  imageAdd() {
    
    this.chooseImg()
      .then(res => {
        return this.uploadImg(res);
      })
      .then(res => {
        console.log(res)
        this.changeArr(config.ImgHost + res.img)
        console.log(config.ImgHost + res.img)
        this.setData({
          addWhat: null,
          activeTab: null
        })
      })
      .catch(err => {
        console.log(err)
      })
  },

  uploadImg(img) {
    let Key = img.substr(img.lastIndexOf('/') + 1); // 这里指定上传的文件名           
    return new Promise((resolve, reject) => {
      cos.postObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: Key,
        FilePath: img,
        onProgress(info) {
          info.img = Key;
          resolve(info)
        }
      });
    })

  },
  chooseImg() {
    var that = this;
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          let img = res.tempFilePaths[0];
          resolve(img)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }
})